package com.alibaba.sample.petstore.dal.dao.cached;

import java.util.List;
import java.util.Map;

import com.alibaba.sample.petstore.dal.dao.ProductDao;
import com.alibaba.sample.petstore.dal.dataobject.Product;

public class CachedProductDao extends AbstractCachedDao<ProductDao> implements ProductDao {
    private final Map<String, Product> productsById = createCache();
    private final Map<String, List> productListsByCategoryId = createCache();

    public CachedProductDao(ProductDao backingDao) {
        super(backingDao);
    }

    public Product getProductById(String productId) {
        Product product = productsById.get(productId);

        if (product == null) {
            product = backingDao.getProductById(productId);
            productsById.put(productId, product);
        }

        return product;
    }

    public List getProductListByCategoryId(String categoryId) {
        List productList = productListsByCategoryId.get(categoryId);

        if (productList == null) {
            productList = backingDao.getProductListByCategoryId(categoryId);
            productListsByCategoryId.put(categoryId, productList);
        }

        return productList;
    }

    public void insertProduct(Product product) {
        backingDao.insertProduct(product);
    }

    public List searchProductList(String keywords) {
        return backingDao.searchProductList(keywords);
    }
}
